package com.mf.all.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mf.all.emuns.enumsPublic.EnumPublicEnableOrDisable;
import com.mf.all.exception.GraceException;
import com.mf.all.service.ServiceUser;
import com.mf.all.utils.UtilsEnum;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.mf.all.entity.dto.DtoDept;
import com.mf.all.entity.req.search.basic.SearchReqDept;
import com.mf.all.mapper.MapperDept;
import com.mf.all.service.ServiceDept;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


@Service
public class ImplServiceDept extends ServiceImpl<MapperDept, DtoDept> implements ServiceDept {
    @Resource
    private ServiceUser serviceUser;


    @Override
    public LambdaQueryWrapper<DtoDept> fillParams(SearchReqDept params) {
        final LambdaQueryWrapper<DtoDept> wrapper = loadQw();
        if (StringUtils.isNotBlank(params.getKey())) {
            wrapper.and(w -> {
                w.like(DtoDept::getDName, params.getKey()).or().like(DtoDept::getDCode, params.getKey());
            });
        }
        wrapper.eq(ObjectUtils.isNotEmpty(params.getPid()), DtoDept::getPid, params.getPid()).eq(ObjectUtils.isNotEmpty(params.getStatus()), DtoDept::getStatus, params.getStatus()).eq(ObjectUtils.isNotEmpty(params.getPrincipalId()), DtoDept::getPrincipalId, params.getPrincipalId());
        return wrapper;
    }

    /**
     * 根据id查询是否有子部门
     */
    private boolean isExistChildDept(Integer id) {
        final LambdaQueryWrapper<DtoDept> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DtoDept::getPid, id);
        return count(wrapper) > 0;
    }

    /**
     * 修改状态
     */
    @Override
    @Transactional
    public void updateStatus(DtoDept dtoDept) {
        UtilsEnum.existsInEnum(EnumPublicEnableOrDisable.class, dtoDept.getStatus());
        if (serviceUser.findByDeptIdCount(dtoDept.getId()) > 0) {
            GraceException.display("该部门下有在职员工, 不可修改部门状态");
        }
        if (isExistChildDept(dtoDept.getId())) {
            GraceException.display("该部门有子部门, 不可直接修改部门状态");
        }
        updateById(dtoDept);
    }


    /**
     * 树形结构列表查询
     */
    @Override
    public List<DtoDept> listTree() {
        final LambdaQueryWrapper<DtoDept> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DtoDept::getStatus, EnumPublicEnableOrDisable.ENABLE.getCode());
        final List<DtoDept> deptList = list(wrapper);
        final List<DtoDept> dtoDeptList = deptList.stream().filter(p -> p.getPid().equals(0)).toList();
        for (DtoDept dtoDept : dtoDeptList) {
            dtoDept.setChildren(setChildren(deptList, dtoDept.getId(), dtoDept.getChildren()));
        }
        return dtoDeptList;
    }

    /**
     * 设置部门下的子部门
     */
    private List<DtoDept> setChildren(List<DtoDept> allDepts, Integer deptId, List<DtoDept> children) {
        if (ObjectUtils.isEmpty(children)) {
            children = new ArrayList<>();
        }

        for (DtoDept allDept : allDepts) {
            if (allDept.getPid().equals(deptId)) {
                children.add(allDept);
            }
        }

        if (!children.isEmpty()) {
            for (DtoDept child : children) {
                child.setChildren(setChildren(allDepts, child.getId(), child.getChildren()));
            }
        }

        return children;

    }

    /**
     * 根据id验证是否有该部门
     */
    @Override
    public void isExistById(Integer id) {
        final LambdaQueryWrapper<DtoDept> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DtoDept::getId, id)
                .eq(DtoDept::getStatus, EnumPublicEnableOrDisable.ENABLE.getCode());
        if (ObjectUtils.isEmpty(getOne(wrapper))) {
            GraceException.display("部门不存在");
        }
    }

    /**
     * 删除部门
     */
    @Override
    @Transactional
    public void deleteById(Integer id) {
        if (serviceUser.findByDeptIdCount(id) > 0) {
            GraceException.display("当前部门有员工无法删除");
        }
        final LambdaQueryWrapper<DtoDept> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DtoDept::getPid, id);
        if (ObjectUtils.isNotEmpty(list(wrapper))) {
            GraceException.display("当前部门有子部门无法删除");
        }
        this.removeById(id);
    }
}